package com.pocket.demo.core.security;

import cn.hutool.json.JSONUtil;
import com.pocket.demo.base.enums.MsgCodeEnum;
import com.pocket.demo.base.utils.ServletUtils;
import com.pocket.demo.core.i18n.MessageSourceService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

/**
 * 用于处理 认证失败 或 未认证的请求。返回 未授权 JSON 消息体。
 *
 * @author zhaozhile
 */
public class JsonAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
    {
        ServletUtils.renderString(response, JSONUtil.toJsonStr(MessageSourceService.getRestResult(MsgCodeEnum.ERROR_UNAUTHENTICATED, new Object[0])));
    }
}
